﻿using System;
using Dan.Common.Extend;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Nest;
using Newtonsoft.Json;

namespace Dan.Common.CusException
{
    [ElasticsearchType(IdProperty = "time", Name = "errorlog")]
    internal class ErrorInfo
    {
        public string time { get; set; }
        public string path { get; set; }
        public string query { get; set; }
        public string formdata { get; set; }
        public string header { get; set; }

        [Text(Analyzer = "ik_max_word", SearchAnalyzer = "ik_max_word")]
        public string message { get; set; }

        public string targetSite { get; set; }
        public string source { get; set; }
        public string stackTrace { get; set; }
        public string innerException { get; set; }
    }

    public class ExceptionMiddlewareDemo : BaseExceptionMiddleware
    {
        
        public ExceptionMiddlewareDemo(RequestDelegate next,
            IHostingEnvironment env,
            ILogger<BaseExceptionMiddleware> logger
        ) : base(next, env, logger)
        {
        }

        public override void AfterAddLog(RequestInfo ri, Exception ex)
        {
            AddRedis(ri, ex);
            AddToEs(ri, ex);
        }

        private void AddRedis(RequestInfo ri, Exception ex)
        {
            
        }

        private void AddToEs(RequestInfo ri, Exception ex)
        {
            
        }

        private ErrorInfo GetExceptionObj(RequestInfo ri, Exception ex)
        {
            var message = ex.Message;
            if (ex is MsgException) message = $"{((MsgException) ex).Message} {message}\r\n";

            if (ex is ValidationException) message = $"{((ValidationException) ex).Message} {message}\r\n";

            return new ErrorInfo
            {
                time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"),
                path = ri.Path,
                query = ri.Query,
                formdata = ri.FormData,
                header = ri.Header,
                message = ex.Message,
                targetSite = ex.TargetSite.SafeToString(),
                source = ex.Source,
                stackTrace = ex.StackTrace,
                innerException = ex.InnerException.SafeToString()
            };
        }
    }

    /// <summary>
    ///     异常中间件扩展
    /// </summary>
    public static class ExceptionMiddlewareExtensions
    {
        /// <summary>
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseExceptionMiddlewareDemo(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ExceptionMiddlewareDemo>();
        }
    }
}